// 分类API请求
import request from '@/utils/request';

// 定义分类数据类型
interface Category {
  id: number;
  name: string;
  description: string;
  parent_id: number;
  level: number;
  sort_order: number;
  created_at: string;
  updated_at: string;
}

// 获取分类列表
export async function listCategories(): Promise<Category[]> {
  try {
    const response = await request.get('/categories/listCategories');
    // 根据后端返回的数据结构进行调整
    return response.data.data || [];
  } catch (error) {
    console.error('获取分类列表失败:', error);
    return [];
  }
}

// 获取单个分类
export async function getCategories(id: number): Promise<Category | null> {
  try {
    const response = await request.get(`/categories/getCategories/${id}`);
    // 根据后端返回的数据结构进行调整
    return response.data.data || null;
  } catch (error) {
    console.error('获取分类失败:', error);
    return null;
  }
}

// 创建分类
export async function createCategory(category: Omit<Category, 'id' | 'created_at' | 'updated_at'>): Promise<Category | null> {
  try {
    const response = await request.post('/categories/saveCateory', category);
    return response.data.data || null;
  } catch (error) {
    console.error('创建分类失败:', error);
    return null;
  }
}

// 更新分类
export async function updateCategory(id: number, category: Partial<Omit<Category, 'id' | 'created_at' | 'updated_at'>>): Promise<Category | null> {
  try {
    const response = await request.put(`/categories/updateCateory/${id}`, category);
    return response.data.data || null;
  } catch (error) {
    console.error('更新分类失败:', error);
    return null;
  }
}

// 删除分类
export async function deleteCategory(id: number): Promise<boolean> {
  try {
    const response = await request.delete(`/categories/delCateory/${id}`);
    // 根据后端返回的数据结构进行调整
    return response.data.code === 200;
  } catch (error) {
    console.error('删除分类失败:', error);
    return false;
  }
}

// 获取子分类
export async function getSubcategories(parentId: number): Promise<any[] | null> {
  try {
    const response = await request.get(`/categories/${parentId}/subcategories`);
    return response.data.data || [];
  } catch (error) {
    console.error('获取子分类失败:', error);
    return null;
  }
}